<template>
	<d2-container>
		<!-- 搜索 -->
		<template slot="header">
			<el-form ref="queryForm" :model="queryForm" class="header-area" label-width="90px" style="height:auto">
				<el-row>
					<el-col :span="5">
						<el-form-item label="商品名称" prop="productName">
							<el-input type="text" v-model="queryForm.productName" placeholder="请输入商品名称"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="商品编码" prop="productCode">
							<el-input type="text" v-model="queryForm.productCode" placeholder="请输入商品编码"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="SKU名称" prop="productSkuName">
							<el-input type="text" v-model="queryForm.productSkuName" placeholder="请输入SKU名称"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="SKU编码" prop="productSkuCode">
							<el-input type="text" v-model="queryForm.productSkuCode" placeholder="请输入SKU编码"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-form-item label="SKU条形码" prop="productBarCode">
							<el-input type="text" v-model="queryForm.productBarCode" placeholder="SKU条形码"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="4">
						<el-form-item label="状态" prop="status">
							<el-select v-model="queryForm.status" placeholder="请选择" style="width: 100%;">
								<el-option label="全部" value=""></el-option>
								<el-option label="下架" value="0"></el-option>
								<el-option label="上架" value="1"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-form-item label="售卖状态" prop="saleStatus">
							<el-select v-model="queryForm.saleStatus" placeholder="请选择" style="width: 100%;">
								<el-option label="全部" value=""></el-option>
								<el-option label="停售" value="0"></el-option>
								<el-option label="在售" value="1"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-form-item label="销售渠道" prop="saleChannel">
							<el-select v-model="queryForm.saleChannel" placeholder="请选择" style="width: 100%;">
								<el-option label="全部" value=""></el-option>
								<el-option label="微信小程序" value="0"></el-option>
								<el-option label="商家/供应商" value="1"></el-option>
								<el-option label="直播平台" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<el-form-item label="创建时间" prop="time">
							<el-date-picker
								v-model="time"
								type="datetimerange"
								:picker-options="pickerOptions"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="timestamp"
								align="right"
								:default-time="['00:00:00', '23:59:59']"
								style="width: 100%;"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<div class="search-submit">
							<el-button type="primary" @click="submitForm('queryForm')">查询</el-button>
							<el-button @click="resetForm('queryForm')">重置</el-button>
							<el-button type="warning" :loading="isExporting" @click="exportSkuSaleList">{{isExporting ? '导出中' : '导出列表'}}</el-button>
						</div>
					</el-col>
				</el-row>
			</el-form>
		</template>

		<!-- 列表部分 -->
		<template>
			<!-- 表格上方的按钮 -->
			<div class="table-header">
				<el-button type="success" @click="batchOperateSaleStatusOn()">批量启售</el-button>
				<el-button type="info" @click="batchOperateSaleStatusStop()">批量停售</el-button>
			</div>

			<!-- 表格 -->
			<!-- 表格统一用 带边框、条纹间隔 的样式 -->
			<el-table :data="tableData" stripe border style="width: 100%" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="40" align="center"></el-table-column>
				<el-table-column type="index" fixed label="序号" width="50" align="center"></el-table-column>
				
				<el-table-column prop="skuThumbImage" label="SKU缩略图" width="80" align="center">
					<template slot-scope="scope">
						<el-image style="width: 35px; height: 35px" :src="scope.row.skuThumbImage" :preview-src-list="[scope.row.skuThumbImage]"></el-image>
					</template>
				</el-table-column>
				
				<el-table-column prop="productName" label="商品名称" align="center" width="150"></el-table-column>
				<el-table-column prop="productCode" label="商品编码" align="center"></el-table-column>
				<el-table-column prop="skuName" label="SKU名称" align="center" width="80"></el-table-column>
				<el-table-column prop="skuCode" label="SKU编码" align="center" width="80"></el-table-column>
				<el-table-column prop="productBarCode" label="SKU条形码" align="center" width="100"></el-table-column>
				
				<el-table-column prop="priceShow" label="原价(元)" align="center"></el-table-column>
				<el-table-column prop="price" label="销售价(元)" align="center"></el-table-column>
				<el-table-column prop="memberPrice" label="会员价(元)" align="center"></el-table-column>
				<el-table-column prop="couponAmount" label="券抵扣金额(元)" align="center"></el-table-column>
				<el-table-column prop="rechargePrice" label="充值会员价(元)" align="center"></el-table-column>
				<el-table-column prop="stock" label="库存" align="center"></el-table-column>
				
				<el-table-column prop="saleChannel" label="销售渠道" align="center" width="100">
					<template slot-scope="scope">
						<el-tag size="small" type="success" v-if="scope.row.saleChannel == 1">商家/供应商</el-tag>
						<el-tag size="small" type="warning" v-else-if="scope.row.saleChannel == 2">直播平台</el-tag>
						<el-tag size="small" v-else>微信小程序</el-tag>
					</template>
				</el-table-column>
				
				<el-table-column prop="status" label="状态" align="center">
					<template slot-scope="scope">
						<el-tag size="small" :type="scope.row.status === 1 ? 'success' : 'warning'" disable-transitions>{{scope.row.status==0 ? "下架" : "上架"}}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="saleStatus" label="售卖状态" align="center">
					<template slot-scope="scope">
						<el-tag size="small" :type="scope.row.saleStatus === 1 ? 'success' : 'info'" disable-transitions>{{scope.row.saleStatus == 0 ? "已停售" : "在售中"}}</el-tag>
					</template>
				</el-table-column>
				
				<el-table-column prop="unitName" label="单位" width="60" align="center"></el-table-column>
				<el-table-column prop="ratio" label="转换系数" width="80" align="center"></el-table-column>
				<el-table-column prop="isSkuPack" label="是否SKU单位" align="center">
					<template slot-scope="scope">
						<el-tag size="small" :type="scope.row.isSkuPack === 1 ? 'primary' : 'success'" disable-transitions>{{scope.row.isSkuPack==1?"是":"否"}}</el-tag>
					</template>
				</el-table-column>
				
				<!-- <el-table-column prop="createTime" label="创建时间" width="95" :formatter="forDateCreate"></el-table-column>
				<el-table-column prop="reviseTime" label="修改时间" width="95" :formatter="forDateRevise"></el-table-column> -->
				
				<el-table-column label="操作" fixed="right" width="230">
					<template slot-scope="scope">
						<div>
							<el-button type="success" size="mini" @click.native.prevent="operateSaleStatusOn(scope.$index, scope.row)" v-if="scope.row.saleStatus==0">启售</el-button>
							<el-button type="info" size="mini" @click.native.prevent="operateSaleStatusStop(scope.$index, scope.row)" v-if="scope.row.saleStatus==1">停售</el-button>
							<el-button type="primary" size="mini" @click.native.prevent="editPrice(scope.row)">调价</el-button>
							<el-button type="primary" size="mini" @click.native.prevent="editStock(scope.row)" v-if="scope.row.stockStatus == 1">调库存</el-button>
						</div>
						<div style="margin-top: 6px;">
							<el-button type="danger" size="mini" @click="delectSkuSale(scope.$index, scope.row)">移除</el-button>
							<el-button type="primary" size="mini" @click="editInfo(scope.row)">编辑</el-button>
							<el-button size="mini" type="primary" plain @click="createQRcode(scope.row.id)">分享码</el-button>
						</div>
						<div style="margin-top: 6px;">
							<el-button type="success" plain size="mini" @click="setExchange(scope.row)">设为兑换商品</el-button>
						</div>
					</template>
				</el-table-column>
			</el-table>
		</template>

		<!-- 翻页 -->
		<template slot="footer">
			<div class="page">
				<el-pagination
					background
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-sizes="[10, 20, 50, 100]"
					:page-size="pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
				></el-pagination>
			</div>
		</template>
		
		<template>
			<!-- 调价弹窗 -->
			<edit-price-dialog
				:isShow="isShowEditPrice"
				:item="currentItem"
				@close="closeEditPrice"
				@submit="fetchData"
			></edit-price-dialog>
			
			<!-- 调库存弹窗 -->
			<edit-stock-dialog
				:isShow="isShowEditStock"
				:item="currentItem"
				@close="closeEditStock"
				@submit="fetchData"
			></edit-stock-dialog>
			
			<!-- 编辑信息弹窗 -->
			<edit-info-dialog
				:isShow="isShowEditInfo"
				:item="currentItem"
				@close="closeEditInfo"
				@submit="fetchData"
			></edit-info-dialog>
			
			<!-- 设置兑换商品弹窗 -->
			<set-exchange-product-dialog
				:isShow="isShowSetExchange"
				:item="currentItem"
				@close="closeSetExchange"
			></set-exchange-product-dialog>
			
			<!-- 分享二维码 -->
			<el-dialog title="商品分享二维码" :visible.sync="showShareQrcode" width="500px" :close-on-click-modal="false" :close-on-press-escape="false" :before-close="closeShareQrcode">
				<div class="share-qrcode" v-if="shareQrcode">
					<img :src="shareQrcode" />
			
					<p>点击右键，保存图片</p>
				</div>
			
				<div class="share-qrcode-loading" v-else>二维码加载中...</div>
			</el-dialog>
		</template>
	</d2-container>
</template>

<script>
	import { findAllProductSkuSaleListByPage, onSaleProductSkuSale, stopSaleProductSkuSale, batchOperateSaleStatus, delProductSkuSale, createQRcode, exportSkuSaleList } from '@api/product/productSkuSale'
	import editPriceDialog from './editPrice'
	import editStockDialog from './editStock'
	import editInfoDialog from './editInfo'
	import setExchangeProductDialog from './setExchange'
	import dayjs from 'dayjs'
	export default {
		name: 'productInfoSku-saleList',
		components: {
			editPriceDialog,
			editStockDialog,
			editInfoDialog,
			setExchangeProductDialog,
		},
		data() {
			return {
				queryForm: {
					productName: '',
					productCode: '',
					productSkuName: '',
					productSkuCode: '',
					productBarCode: '',
					status: '',
					saleStatus: '',
					saleChannel: '',
					createTimeBegin: '',
					createTimeEnd: ''
				},
				time: [],
				pickerOptions: {
					shortcuts: [{
							text: '最近一周',
							onClick(picker) {
								const end = new Date()
								const start = new Date()
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
								picker.$emit('pick', [start, end])
							}
						},
						{
							text: '最近一个月',
							onClick(picker) {
								const end = new Date()
								const start = new Date()
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
								picker.$emit('pick', [start, end])
							}
						},
						{
							text: '最近三个月',
							onClick(picker) {
								const end = new Date()
								const start = new Date()
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
								picker.$emit('pick', [start, end])
							}
						}
					]
				},
				
				tableData: [],
				currentPage: 1,
				pageSize: 10,
				total: 0,
				multipleSelection: [],
				isExporting: false, //导出状态
				
				isShowEditPrice: false,
				isShowEditStock: false,
				isShowEditInfo: false,
				isShowSetExchange: false,
				currentItem: {},
				
				showShareQrcode: false,
				shareQrcode: '', //分享二维码链接
			}
		},
		methods: {
			fetchData() {
				this.loading = true;
				this.queryForm.createTimeBegin = this.time[0] == null ? '' : dayjs(this.time[0]).format('YYYY-MM-DD HH:mm:ss');
				this.queryForm.createTimeEnd = this.time[1] == null ? '' : dayjs(this.time[1]).format('YYYY-MM-DD HH:mm:ss');
				
				findAllProductSkuSaleListByPage({
					productName: this.queryForm.productName,
					productCode: this.queryForm.productCode,
					productSkuName: this.queryForm.productSkuName,
					productSkuCode: this.queryForm.productSkuCode,
					productBarCode: this.queryForm.productBarCode,
					status: this.queryForm.status,
					saleStatus: this.queryForm.saleStatus,
					saleChannel: this.queryForm.saleChannel,
					createTimeBegin: this.queryForm.createTimeBegin,
					createTimeEnd: this.queryForm.createTimeEnd,
					currentPage: this.currentPage,
					pageSize: this.pageSize
				})
				.then(res => {
					this.tableData = res.data.content;
					this.total = res.data.total;
					this.loading = false;
				})
				.catch(err => {
					console.log('err', err);
					this.loading = false;
				})
			},
			handleSizeChange(val) {
				this.pageSize = val;
				this.fetchData();
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.fetchData();
			},
			resetPage() {
				this.currentPage = 1;
				this.pageSize = 10;
				this.total = 0;
			},
			
			exportSkuSaleList() { //导出销售列表
				if(this.isExporting) {
					return;
				}
				this.isExporting = true;
				
				this.queryForm.createTimeBegin = this.time[0] == null ? '' : dayjs(this.time[0]).format('YYYY-MM-DD HH:mm:ss');
				this.queryForm.createTimeEnd = this.time[1] == null ? '' : dayjs(this.time[1]).format('YYYY-MM-DD HH:mm:ss');
				
				exportSkuSaleList({
					productName: this.queryForm.productName,
					productCode: this.queryForm.productCode,
					productSkuName: this.queryForm.productSkuName,
					productSkuCode: this.queryForm.productSkuCode,
					productBarCode: this.queryForm.productBarCode,
					status: this.queryForm.status,
					saleStatus: this.queryForm.saleStatus,
					saleChannel: this.queryForm.saleChannel,
					createTimeBegin: this.queryForm.createTimeBegin,
					createTimeEnd: this.queryForm.createTimeEnd,
				})
				.then(res => {
					var blob = new Blob([res.data], {
						type: 'application/vnd.ms-excel'
					});
					var filename = res.headers.filename;
					var downloadElement = document.createElement('a');
					var href = window.URL.createObjectURL(blob); // 创建下载的链接
					downloadElement.style.display = 'none';
					downloadElement.href = href;
					downloadElement.download = filename; // 下载后文件名
					document.body.appendChild(downloadElement);
					downloadElement.click(); // 点击下载
					document.body.removeChild(downloadElement); // 下载完成移除元素
					window.URL.revokeObjectURL(href); // 释放掉blob对象
					this.isExporting = false;
				})
				.catch(err => {
					console.log('err', err);
					this.isExporting = false;
				})
			},
			
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			forDateCreate(row, column) {
				return row.createTime == null ? "" : dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss');
			},
			forDateRevise(row, column) {
				return row.reviseTime == null ? '' : dayjs(row.reviseTime).format('YYYY-MM-DD HH:mm:ss');
			},
			
			submitForm(formName) {
				this.resetPage();
				this.fetchData();
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
				this.time = [];
				this.resetPage();
				this.fetchData();
			},
			
			// 启售
			operateSaleStatusOn(index, row) {
				this.$confirm("确认启售【" + row.skuName + "】？").then(_ => {
					this.loading = true;
					
					onSaleProductSkuSale({
						id: row.id
					})
						.then(res => {
							if (res.code == '000000') {
								this.$message({
									message: res.message,
									type: "success"
								});
								this.fetchData();
								this.loading = false;
							} else {
								this.$message({
									message: res.message,
									type: 'error'
								});
								return;
							}
						})
						.catch(err => {
							console.log("err", err);
							this.loading = false;
						});
					});
			},
			// 停售
			operateSaleStatusStop(index, row) {
				this.$confirm("确认停售【" + row.skuName + "】？").then(_ => {
					this.loading = true;
					
					stopSaleProductSkuSale({
						id: row.id
					})
						.then(res => {
							if (res.code == '000000') {
								this.$message({
									message: res.message,
									type: "success"
								});
								this.fetchData();
								this.loading = false;
							} else {
								this.$message({
									message: res.message,
									type: 'error'
								});
								return;
							}
						})
						.catch(err => {
							console.log("err", err);
							this.loading = false;
						});
				});
			},
			// 批量启售
			batchOperateSaleStatusOn() {
				let offFlag = false;
				
				if (this.multipleSelection.length <= 0) {
					this.$message.warning('请选择需要批量启售的记录');
					return;
				}
				this.multipleSelection.forEach(function(row) {
					if (row.saleStatus == 1) {
						offFlag = true;
					}
				});
				
				if (offFlag) {
					this.$message.warning('选项中存在在售中的记录');
					return;
				}

				this.$confirm('确定批量设置已选中' + this.multipleSelection.length + '条记录为【在售中】吗？')
					.then(() => {
						let ids = '';
						this.multipleSelection.forEach(row => {
							ids = ids + ',' + row.id;
						})
						// 截取第1个之后所有的字符
						ids = ids.slice(1);
						
						batchOperateSaleStatus({
							ids: ids,
							saleStatus: 1
						})
							.then(res => {
								if (res.code == '000000') {
									this.$message({
										message: res.message,
										type: "success"
									});
									this.fetchData();
									this.loading = false;
								} else {
									this.$message({
										message: res.message,
										type: 'error'
									});
									return;
								}
							})
							.catch(err => {
								console.log('err', err);
								this.loading = false;
							})
					}).catch(err => {
						console.log("err", err);
						this.loading = false;
					})
			},
			// 批量停售
			batchOperateSaleStatusStop() {
				let upFlag = false;
				
				if (this.multipleSelection.length <= 0) {
					this.$message.warning('请选择需要批量停售的记录');
					return;
				}
				this.multipleSelection.forEach(function(row) {
					if (row.saleStatus == 0) {
						upFlag = true;
					}
				})
				if (upFlag) {
					this.$message.warning('选项中存在已停售的记录');
					return;
				}

				this.$confirm('确定批量设置已选中' + this.multipleSelection.length + '条记录为【已停售】吗？')
					.then(() => {
						let ids = '';
						this.multipleSelection.forEach(row => {
							ids = ids + ',' + row.id;
						})
						// 截取第1个之后所有的字符
						ids = ids.slice(1);
						
						batchOperateSaleStatus({
							ids: ids,
							saleStatus: 0
						})
							.then(res => {
								if (res.code == '000000') {
									this.$message({
										message: res.message,
										type: "success"
									});
									this.fetchData();
									this.loading = false;
								} else {
									this.$message({
										message: res.message,
										type: 'error'
									});
									return;
								}
							})
							.catch(err => {
								console.log('err', err);
								this.loading = false;
							})
					}).catch(err => {
						console.log("err", err);
						this.loading = false;
					})
			},
			
			editPrice(item) { //打开调价弹窗
				if(item.saleStatus === 1) {
					this.$message.error('请先停售商品再进行操作！');
					return;
				}
				this.currentItem = item;
				this.isShowEditPrice = true;
			},
			closeEditPrice() {
				this.isShowEditPrice = false;
			},
			
			editStock(item) { //打开调整库存弹窗
				if(item.saleStatus === 1) {
					this.$message.error('请先停售商品再进行操作！');
					return;
				}
				this.currentItem = item;
				this.isShowEditStock = true;
			},
			closeEditStock() {
				this.isShowEditStock = false;
			},
			
			editInfo(item) { //打开编辑信息弹窗
				if(item.saleStatus === 1) {
					this.$message.error('请先停售商品再进行操作！');
					return;
				}
				this.currentItem = item;
				this.isShowEditInfo = true;
			},
			closeEditInfo() {
				this.isShowEditInfo = false;
			},
			
			setExchange(item) { //打开设置兑换商品弹窗
				this.currentItem = item;
				this.isShowSetExchange = true;
			},
			closeSetExchange() {
				this.isShowSetExchange = false;
			},
			
			delectSkuSale(index, item) { // 删除sku销售
				this.$confirm(`您是否确认删除SKU销售【名称：${item.skuName}，单位：${item.unitName}？】`, '温馨提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						delProductSkuSale({
							id: item.id
						})
							.then(res => {
								if (res.code == '000000') {
									this.$message.success('删除成功');
									this.fetchData();
									this.loading = false;
								} else {
									this.$message({
										message: res.message,
										type: 'error'
									});
									return;
								}
							})
							.catch(err => {
								console.log('err', err);
								this.loading = false;
							})
					})
			},
			
			createQRcode(id) { //生成分享二维码
				this.showShareQrcode = true;
				createQRcode({
					skuSaleId: id,
				})
					.then(res => {
						this.shareQrcode = res.data;
					})
			},
			closeShareQrcode() {
				this.showShareQrcode = false;
				this.shareQrcode = '';
			}
		},
		mounted() {
			this.fetchData();
		},
	}
</script>

<style lang="scss" scoped>
	.share-qrcode {
		width: 100%;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		display: flex;
		img {
			width: 300px;
			height: 300px;
		}
		p {
			height: 30px;
			font-size: 18px;
			margin-top: 30px;
		}
	}
	
	.share-qrcode-loading {
		width: 100%;
		height: 360px;
		font-size: 18px;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		display: flex;
	}
</style>